<?php

class NOTEX {

    const DEFAULT_TOKEN = 'token';
    var $token;
    var $usage;

    // Create a new NOTEX object and check the app token file exists

    function __construct()
    {
        $token = $this->token = $_REQUEST['token'];
        if (!$token) $token = NOTEX::DEFAULT_TOKEN;
        if (!file_exists("../../$token"))
            $this->error("No token $token");
    }

    // Set the usage information with parameters and a description

    function usage($desc, $params = null)
    {
        $xml = "  <params>\n";
        while (list($param, $text) = each($params))
        {
            $xml .= "    <param desc=\"$text\">$param</param>\n";
        }
        $xml .= "  </params>\n";
        if ($desc) $xml .= "  <description>$desc</description>\n";
        if ($params) $this->usage = "<usage>\n$xml</usage>\n";
        return $this->usage;
    }

    // Display an error message as XML and exit the script

    function error($message)
    {
        header('Content-type: text/xml');
        $out = "<error>\n<message>$message</message>\n";
        $out .= $this->usage;
        $out .= "</error>\n";
        print $out;
        exit;
    }
}

// Return a parameter or a default value

function param($param, $default = '')
{
    $value = $_REQUEST[$param];
    return $value ? $value : $default;
}

// GET the contents of a URL

function GET($url)
{
    $url = _full_url($url);
    return file_get_contents($url);
}

// POST to a URL and return its response

function POST($url, $data, $optional_headers = null)
{
    $url = _full_url($url);

    // Set up POST parameters
    $params = array('http' => array(
                        'method'  => 'post',
                        'content' => $data,
                    ));
    if ($optional_headers !== null)
        $params['http']['header'] = $optional_headers;

    // Send the POST request
    $ctx = stream_context_create($params);
    $fp = @fopen($url, 'rb', false, $ctx);
    if (!$fp) return '';

    // Get the response and return it
    $response = @stream_get_contents($fp);
    if ($response === false) return '';

    return $response;
}

// Turn a relative URL into an absolute URL

function _full_url($url)
{
    if (!preg_match('/^https?:\/\//i', $url))
    {
        $host = $_SERVER['HTTP_HOST'];
        if (substr($url, 0, 1) != '/')
            $url = preg_replace('/[^\/]+$/', '', $_SERVER['PHP_SELF']).$url;
        $url = "http://$host$url";
    }
    return $url;
}

// END
